<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="只允许选中第三级菜单" type="warning" center :closable="false"></el-alert>
      <el-row>
        <span>选择商品分类:</span>
        <!-- 渲染级链选择框 -->
        <el-cascader
          v-model="selectCateKeys"
          :options="cateList"
          :props="catProps"
          @change="cateListChange"
        ></el-cascader>
      </el-row>

      <!-- tab页签区域 -->

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加动态参数</el-button>

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                <!-- 可修改的tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDiag(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加静态属性</el-button>

          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
             <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                <!-- 可修改的tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>




            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDiag(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加动态属性和静态参数的弹框 -->

      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDiagClose"
      >
        <!-- from表单 -->

        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDiagBtn">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑动态属性和静态参数的弹框 -->

      <el-dialog
        :title="'编辑'+titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDiagClose"
      >
        <!-- from表单 -->

        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDiagBtn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
export default {
  data() {
    return {
      cateList: [],
      catProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        children: 'children',
        label: 'cat_name'
      },
      // 级连选择框选中的值的id
      selectCateKeys: [],
      // 被激活的页签
      activeName: 'many',
      // 获取的动态参数数据
      manyTableData: [],
      // 获取的静态属性的数据
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 编辑
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 已经定义为私有属性了
      // 可编辑的tag标签
      // inputVisible:false,
      // 可编辑标签的输入值
      // inputValue:''
    };
  },
  methods: {
    async getCateList() {
      let { data: res } = await this.axios.get('categories');
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('请求出错');
      }
      this.cateList = res.data;
    },
    async cateListChange() {
      // console.log(this.selectCateKeys);
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        // 如果长度不等于3 需要请求table表单
        this.manyTableData=[];
        this.onlyTableData=[];
        return;
      }
      // 接下来获取所有的参数数据
      this.getParamsData();
    },
    // tab页签切换事件
    handleTabClick() {
      // console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData() {
      let { data: res } = await this.axios.get(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('请求错误');
      }
      res.data.forEach(item => {
        // 判断item.attr_vals的长度 如果为空直接返回一个空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        // 控制文本框的显示和隐藏
        item.inputValue='';
        item.inputVisible=false
      });
      console.log(res.data);

      // 判断获取到的数据是静态数据还是动态数据然后分开存储
      if (this.activeName == 'many') {
        this.manyTableData = res.data;
      }
      if (this.activeName == 'only') {
        this.onlyTableData = res.data;
      }
    },
    // 添加属性的按钮
    addDiagClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击添加确定按钮
    async addDiagBtn() {
      // 发起提交请求
      let { data: res } = await this.axios.post(
        `categories/${this.cateID}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        }
      );
      // console.log(res);
      if (res.meta.status !== 201) {
        return this.$message.error('添加出错，请重试');
      }
      this.$message.success('添加成功');
      this.getParamsData();

      this.addDialogVisible = false;
    },
    // 编辑属性按钮
    async showEditDiag(attr_id) {
      let { data: res } = await this.axios.get(
        `categories/${this.cateID}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息出错');
      }
      this.editForm = res.data;
      //  console.log(this.editForm);

      this.editDialogVisible = true;
    },
    editDiagClose() {
      this.$refs.editFormRef.resetFields();
    },
    editDiagBtn() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          let { data: res } = await this.axios.put(
            `categories/${this.cateID}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName
            }
          );
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error('更新出错');
          }
          this.$message.success('更新成功');
          this.getParamsData();
        }
      });
      this.editDialogVisible = false;
    },
    // 根据id删除对应的属性
    async removeById(attr_id) {
      console.log(attr_id);

      let { data: res } = await this.axios.delete(
        `categories/${this.cateID}/attributes/${attr_id}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败');
      }
      this.$message.success('删除成功');
      this.getParamsData();
    },
     // 可动态编辑的tag标签的事件
    handleInputConfirm(row) {
     if(row.inputValue.trim().length==0){
       row.inputValue=''
       row.inputVisible=false
       return
     }
    //  如果用户输入了数据则需要进行处理
    // 将用户输入的数据push到所有的循环的对象中 然后再次提交给后台
    row.attr_vals.push(row.inputValue);
    row.inputValue='';
    row.inputVisible=false
    // 发起请求保存数据
    // 需要注意的是attr_vars需要转化为字符串后再提交

    this.saveAttrVals(row)
      },
    showInput(row){
      // 做切换使用
      row.inputVisible=true
      // 让文本框自动获得焦点
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除标签
    handleClose(index,row){
      // 1.先删除本地 然后再发起请求
      row.attr_vals.splice(index,1);
      // 然后发起请求进行提交
      this.saveAttrVals(row)

    },
    // 将对数据提交到远程服务器进行保存提交的动作
    async saveAttrVals(row){
          // 需要注意的是attr_vars需要转化为字符串后再提交
      let {data:res}=await this.axios.put(`categories/${this.cateID}/attributes/${row.attr_id}`,{
      attr_name:row.attr_name,
      attr_sel:this.activeName,
      // attr_vals需要转化为字符转
      attr_vals:row.attr_vals.join(' ')
    })
    console.log(res);
    if(res.meta.status!==200){
      return this.$message.error('提交出错')
    }
    this.$message.success('修改参数成功')

    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    // 如果按钮需要被禁用则返回true 否则返回false
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateID() {
      if (this.selectCateKeys.length == 3) {
        return this.selectCateKeys[2];
      } else {
        return null;
      }
    },
    titleText() {
      if (this.activeName == 'many') {
        return '动态参数';
      } else {
        return '静态属性';
      }
    }
   
  }
};
</script>
<style scoped lang="less">
.el-card,
.el-row {
  margin-top: 15px;
}
.el-tag {
  margin: 0 5px;
}
.input-new-tag{
  width:120px;
}
</style>